<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2017-03-17
 * Time: 15:37
 */

namespace app\src\sunsun\filterVat\action;

use app\src\base\helper\ResultHelper;
use app\src\base\helper\ValidateHelper;
use app\src\sunsun\common\helper\DeviceInfoPollHelper;
use app\src\sunsun\common\logic\UserDeviceLogic;
use app\src\sunsun\filterVat\logic\FilterVatDeviceLogic;
use sunsun\filter_vat\req\FilterVatDeviceInfoReq;


/**
 * Class FilterVatDeviceInfoAction
 * 获取设备信息
 * @package app\src\sunsun\filterVat
 */
class FilterVatDeviceInfoAction extends FilterVatBaseAction
{
    /**
     * 获取设备信息
     * @param $did
     * @param int $uid
     * @param int $getDeviceInfo
     * @return array
     */
    public function deviceInfo($did, $uid = 0, $getDeviceInfo = 1)
    {
        if (intval($uid) < 0) {
            return ResultHelper::error('该用户不存在');
        }
        if ($uid == 0) {
            $deviceInfo = [];
        } else {
            $result = (new UserDeviceLogic())->getInfo(['uid' => $uid, 'did' => $did]);
            if (!ValidateHelper::legalArrayResult($result)) {
                return ResultHelper::error('该设备信息不存在');
            }
            $deviceInfo = $result['info'];
        }

        $result = (new FilterVatDeviceLogic())->getInfo(['did' => $did]);
        if (!ValidateHelper::legalArrayResult($result)) {
            return ResultHelper::error('该设备信息不存在');
        }

        $result['info'] = array_merge($this->processDevice($result['info']), $deviceInfo);
        $deviceInfo = $result['info'];
        if ($getDeviceInfo) {
            DeviceInfoPollHelper::poll($deviceInfo, new FilterVatDeviceInfoReq(), new FilterVatDeviceLogic());
        }
//        $now = time();
//        //设备信息3s以内如果更新过了，则不请求获取设备状态
//        if(!empty($deviceInfo['tcp_client_id']) && $deviceInfo['tcp_last_send_time'] <  $now - 1) {
//            $req = new FilterVatDeviceInfoReq();
//            $req->setSn(SnHelper::getSn());
//            // ============START 用于统计网络延时=========
//            $session = Gateway::getSession($deviceInfo['tcp_client_id']);
//            Gateway::updateSession($deviceInfo['tcp_client_id'],DelayStaticsHelper::init($session, $req));
//            // ============END  用于统计网络延时==========
//
//            $ret = $this->sendReqToFilterVatClient($did, $req);
//
//            if($ret['status']){
//                // 只有成功后才更新该时间
//                (new FilterVatDeviceLogic())->save(['did'=>$did],['tcp_last_send_time'=>$now]);
//            }
//        }

        return $result;
    }

    private function processDevice($info)
    {
        if (!is_array($info)) {
            return $info;
        }
        $info['is_disconnect'] = 0;
        //如果tcp通道id为空，则设备已断开
        if (empty($info['tcp_client_id'])) {
            $info['is_disconnect'] = 2;
        }
        return $info;
    }
}